use anyhow::Result;
use std::sync::Arc;
use tokio::net::TcpListener;
use tracing::{info, error, warn};

use crate::config::ServerConfig;
use crate::database::Database;
use super::session::FtpSession;
use crate::services::AuthManager;

pub struct FtpServer {
    config: ServerConfig,
    database: Arc<Database>,
}

impl FtpServer {
    pub async fn new(config: ServerConfig, database: Database) -> Result<Self> {
        Ok(Self {
            config,
            database: Arc::new(database),
        })
    }
    
    pub async fn start(&self) -> Result<()> {
        let addr = format!("{}:{}", self.config.server.host, self.config.server.port);
        let listener = TcpListener::bind(&addr).await?;
        
        info!("FTP Server listening on {}", addr);
        
        loop {
            match listener.accept().await {
                Ok((stream, peer_addr)) => {
                    info!("New connection from {}", peer_addr);
                    
                    let database = Arc::clone(&self.database);
                    let config = self.config.clone();
                    
                    tokio::spawn(async move {
                        if let Err(e) = Self::handle_connection(stream, peer_addr, database, config).await {
                            error!("Connection error: {}", e);
                        }
                    });
                }
                Err(e) => {
                    error!("Failed to accept connection: {}", e);
                }
            }
        }
    }
    
    async fn handle_connection(
        stream: tokio::net::TcpStream,
        peer_addr: std::net::SocketAddr,
        database: Arc<Database>,
        config: ServerConfig,
    ) -> Result<()> {
        let auth_manager = AuthManager::new(database.pool().clone());
        let mut session = FtpSession::new(stream, peer_addr, database, config, auth_manager).await?;
        
        // 发送欢迎消息
        session.send_response(shared::types::FtpResponse::new(
            shared::types::FtpResponseCode::ServiceReady,
            "FTP Server Ready"
        )).await?;
        
        // 处理客户端命令
        session.run().await?;
        
        Ok(())
    }
}
